package service;


import com.alibaba.fastjson.JSONObject;
import utils.UserManager;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/getUsers")
public class getUsersService extends HttpServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        // 设置默认值
        int page = 1; // 默认页码
        int limit = 10; // 默认每页显示数量

        // 尝试从请求中获取page和limit参数，并设置默认值
        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        if (pageParam != null && pageParam.matches("\\d+")) {
            page = Integer.parseInt(pageParam);
        }
        if (limitParam != null && limitParam.matches("\\d+")) {
            limit = Integer.parseInt(limitParam);
        }

        System.out.println("page: " + page + " limit: " + limit);
        JSONObject resJson = new JSONObject();
        try {
            resJson = UserManager.getUsersInfoAsJson(page, limit);
        } catch (Exception e) {
            e.printStackTrace();
            // 可能需要处理异常情况，比如返回错误信息
            resJson.put("error", "Failed to retrieve user info");
        }

        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(resJson.toJSONString());
    }
}